<script>
	import store from '@/store/index.js'; //需要引入store
	export default {
		data() {
			return {
				socketTask: null,
				is_open_socket: false
			}
		},

		onLaunch: function() {
			
			this.socketTask = uni.connectSocket({
					url: 'ws://192.168.1.128:8001',
					success() {
						console.log('创建连接成功')
					},
					fail: (res) => {
						console.log('创建连接失败：', res)
					}
				}),
				this.socketTask.onOpen(() => {
					console.log('服务器连接打开')
					this.is_open_socket = true
				})
			this.socketTask.onMessage((res) => {
				var data = JSON.parse(res.data)
				console.log(data);
				store.commit("setAllData", data)
				store.commit('setAllDevice', data.name)
			})
			this.socketTask.onError((res) => {
				this.is_open_socket = false
				console.log('服务器连接错误', res)
			})
			this.socketTask.onClose(() => {
				this.is_open_socket = false
				console.log('服务器连接关闭')
			})
		},
		computed: {
			sendMsg() {
				store.state.sendMsg
			}
		},
		watch: {
			sendMsg: {
				deep: true,
				handler(res) {
					var datas = store.state.sendMsg
					console.log(datas)
					this.socketTask.send({ //向后端发送信息
						data: JSON.stringify(datas)
					})
				}
			}
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		onUnload() {
			uni.closeSocket({
				success() {
					console.log('关闭连接成功')
				}
			});
		}

	}
</script>

<style>
	@import url("@/colorui/icon.css");
	@import url("@/colorui/main.css");
</style>
